package com.wjm.blog.common.util;

import java.io.*;

/**
 * @author BUG WRITTER
 * @date 2022/9/28 15:49
 */
public class FileUtil {

    public static String getFilepath() {
        String filepath = "/home/dataTemp/";
        if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
            filepath = "C:\\home\\dataTemp\\";
        }
        return filepath;
    }

    /**
     * * 方法中传入的参数分别为
     * * filePath:为生成的file文件地址，地址后要以\（File.separator）结尾，
     * * fileName：为生成的file文件名称
     *
     * @param bytes
     * @param fileName
     * @return
     */
    public static File bytes2File(byte[] bytes, String fileName) {
        String filePath = getFilepath();

        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {

            file = new File(filePath + fileName);
            if (!file.getParentFile().exists()) {
                //文件夹不存在 生成
                file.getParentFile().mkdirs();
            }
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }

    /**
     * 根据文件生成byte数组
     *
     * @param url
     * @return
     */
    public static byte[] file2Byte(String url) {
        File file = new File(url);
        byte[] data = new byte[0];
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            data = bos.toByteArray();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return data;
    }

    /**
     * 删除文件
     *
     * @param fileName
     */
    public static void deleteFile(String fileName) {
        String filePath = getFilepath();
        File tarGetFile = new File(filePath+fileName);
        if (tarGetFile.exists()) {
            tarGetFile.delete();
        }
    }


}
